package com.yufei.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yufei.common.R;
import com.yufei.dto.DishDto;
import com.yufei.dto.SetmealDto;
import com.yufei.entity.*;
import com.yufei.service.CategoryService;
import com.yufei.service.DishService;
import com.yufei.service.SetmealDishService;
import com.yufei.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 获取全部套餐信息分页
     * @param page 页数
     * @param pageSize 页大小
     * @return 返回分页对象
     */
    @GetMapping("/setmeal/page")
    public R<Page<SetmealDto>> getSetmealPage(Integer page, Integer pageSize, Setmeal setmeal) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();

        //判断是否有模糊查询,有套餐名就是模糊查询
        String name = setmeal.getName();
        //添加模糊查询条件
        wrapper.like(StringUtils.hasText(name),"name", name);

        //查询is_deleted为0的，即没有被删除的
        wrapper.eq("is_deleted", 0);
        setmealPage = setmealService.page(setmealPage, wrapper);

        // 创建一个新的分页对象来存放Dto类型的数据
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(setmealPage, setmealDtoPage,"records");
        List<Setmeal> records = setmealPage.getRecords();
        //处理获取
        List<SetmealDto> collect = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //将setmeal放到setmealDto中
            BeanUtils.copyProperties(item, setmealDto);
            Category category = categoryService.getById(setmealDto.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(collect);
        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     * @param ids 使用string接受，方便批量删除
     * @return
     */
    @DeleteMapping("/setmeal")
    public R<String> deleteSetmeal(String ids) {
        // 处理 ids 参数，转换为一个列表
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        for (Long id : idList) {
            UpdateWrapper<Setmeal> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", id);
            wrapper.set("is_deleted", 1);
            //更新is_deleted为1，标识删除
            setmealService.update(wrapper);

            //修改setmeal_dish中套餐对应的菜品isdeleted为1
            UpdateWrapper updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("setmeal_id", id);
            updateWrapper.set("is_deleted", 1);
            setmealDishService.update(updateWrapper);
        }
        return R.success("删除成功！");
    }

    // 查询详情接口
    @GetMapping("/setmeal/{id}")
    public R<SetmealDto> querySetmealById(@PathVariable Long id) {
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        //查询种类名并放入dto中
        setmealDto.setCategoryName(categoryService.getById(setmeal.getCategoryId()).getName());
        //查询该套餐对应的菜品
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("setmeal_id", id);
        queryWrapper.eq("is_deleted",0);
        List list = setmealDishService.list(queryWrapper);
        //放到setmealDto中
        setmealDto.setSetmealDishes(list);
        return R.success(setmealDto);
    }
    /**
     * 保存修改
     */
    @PutMapping("/setmeal")
    public R<String> editSetmeal(HttpServletRequest request, @RequestBody SetmealDto setmealDto) {
        Long employee1 = (Long) request.getSession().getAttribute("employee");
        //更新修改信息
        setmealDto.setUpdateTime(new Date());
        setmealDto.setUpdateUser(employee1);
        //setmealdish表可以直接更新
        setmealService.saveOrUpdate(setmealDto);
        //先把原来对应的菜品删除，即对应的is_deleted置为1
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("setmeal_id", setmealDto.getId());
        wrapper.set("is_deleted", 1);
        setmealDishService.update(wrapper);
        //再新增加
        Long setmealId = setmealDto.getId();
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishList) {
            //传递必要信息
            setmealDish.setSetmealId(setmealId);
            //获取菜品id
            Long dishId = setmealDish.getDishId();
            setmealDish.setDishId(dishId);
            setmealDish.setCreateTime(new Date());
            setmealDish.setUpdateTime(new Date());
            setmealDish.setCreateUser(employee1);
            setmealDish.setUpdateUser(employee1);
        }
        boolean isok = setmealDishService.saveBatch(setmealDishList);
        if(isok) {
            return R.success("更新成功！");
        }
        return R.error("更新失败！");
    }

    @PostMapping("/setmeal")
    public R<String> addSetmeal(HttpServletRequest request, @RequestBody SetmealDto setmealDto) {
        Long employee1 = (Long) request.getSession().getAttribute("employee");
        setmealDto.setCreateTime(new Date());
        setmealDto.setUpdateTime(new Date());
        setmealDto.setCreateUser(employee1);
        setmealDto.setUpdateUser(employee1);
        //保存套餐到套餐表
        boolean isok = setmealService.save(setmealDto);

        /**
         * 处理保存套餐对应菜品到setmeal_dish表
         */
        //获取套餐id
        Long setmealId = setmealDto.getId();

        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishList) {
            setmealDish.setSetmealId(setmealId);
            //获取必要信息
            setmealDish.setCreateTime(new Date());
            setmealDish.setUpdateTime(setmealDto.getUpdateTime());
            setmealDish.setCreateUser(employee1);
            setmealDish.setUpdateUser(employee1);
        }
        //批量保存
        boolean isok1 = setmealDishService.saveBatch(setmealDishList);
        if(isok && isok1){
            return R.success("添加成功！");
        }else {
            return R.error("添加失败!");
        }
    }
    //批量起售禁售对应接口
    @PostMapping("/setmeal/status/{status}")
    public R<String> setmealStatusByStatus(HttpServletRequest request, @PathVariable Integer status , String ids) {
        Long employee1 = (Long) request.getSession().getAttribute("employee");

        // 处理 ids 参数，转换为一个列表
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        for (Long id : idList) {
            Setmeal setmeal = setmealService.getById(id);
            //更新状态
            setmeal.setStatus(status);
            //设置更新时间
            setmeal.setUpdateTime(new Date());
            //设置更新人员
            setmeal.setUpdateUser(employee1);

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", setmeal.getId());
            setmealService.update(setmeal, queryWrapper);
        }
        return R.success("更新成功！");
    }
}
